#include "Thread.hpp"
#include <unistd.h>
#include <cstdio>

// 应用方的视角：自动给线程命名
std::string GetThreadName()
{
    static int number = 1;
    char name[64];
    snprintf(name, sizeof(name), "Thread-%d", number++);
    return name;
}

int ticket = 10000;     // 全局的共享资源

void GetTicket(std::string name)
{
    while(true)
    {
        if(ticket > 0)
        {
            usleep(1000);   // 充当抢票花费的时间
            printf("%s get a ticket: %d\n", name.c_str(), ticket);
            ticket--;
        }
        else
        {
            break;
        }

        // 实际情况还有后续的动作
    }
}

int main()
{
    std::string name1 = GetThreadName();
    Thread<std::string> t1(name1, GetTicket, name1);

    std::string name2 = GetThreadName();
    Thread<std::string> t2(name2, GetTicket, name2);

    std::string name3 = GetThreadName();
    Thread<std::string> t3(name3, GetTicket, name3);

    std::string name4 = GetThreadName();
    Thread<std::string> t4(name4, GetTicket, name4);

    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();

    t1.Join();
    t2.Join();
    t3.Join();
    t4.Join();

    return 0;
}